import dynamic from 'next/dynamic'
import Layout from '@c/layout'
import message from '@c/message'
import Responsive from '@c/responsive'
import VideoPlayer from '@c/video/video-player'
import Image from '@c/image'
import styles from './live.module.scss'
import { useEffect, useState, useMemo } from 'react'
import {
  getSourceList,
  getLiveDesc,
  getGroupChannel,
} from '@/api/live'
import { liveCancelCollected,liveCollected,getLiveCollected } from '@/api/history-collect'
import cm from 'classnames'
import { useShowLogin } from '@/utils/hooks'
import { isPureNumber } from '@/utils/utils'
import { channelClickReport } from '@/utils/report'
import { useRecoilValue } from 'recoil'
import { userInfo } from '@/store'
import Link from 'next/link'
import Copy from 'clipboard'
import { liveReport, scoreTaskFinishedReport } from '@/utils/report'
import { taskFinished } from '@/api/score'
import Living from '@c/live-icon'
import { useRouter } from 'next/router'

const DownloadPhone = dynamic(() => import('@c/download/download-phone'))
const DownloadTv = dynamic(() => import('@c/download/download-tv'))

const Index = props => {
  const router = useRouter()
  const user = useRecoilValue(userInfo)
  const { currChannelUrl, name, desc, purl, liveId, liveImg, list, lineArr } = props
  const setShowLogin = useShowLogin()
  const [isCollected, setCollected] = useState(false) //直播是否收藏
  const setErrorCode = VideoPlayer.useSetErrorCode()
  // 直播是否收藏
  const getLiveSelectStatus = () => {
    const token = localStorage.getItem('token')
    if (token) {
      getLiveCollected(liveId, token).then(res => setCollected(res?.data?.isFavorite))
    }
  }

  useEffect(() => {
    getLiveSelectStatus()
  }, [purl])

  useEffect(() => {
    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [])
  // 验证是否是VIP用户，不是则ban src
  useEffect(() => {
    setErrorCode(0)
    if (typeof user.token !== 'undefined' && !user.token) {
      setErrorCode('7')
    } else if (typeof user.isVip !== 'undefined' && !user.isVip) {
      setErrorCode('5')
    }
  }, [user, purl])

  // 直播历史记录信息记录
  useEffect(() => {
    window.varLiveReport = {
      id: liveId,
      img: liveImg,
      name,
      playProgress: 91,
      url: currChannelUrl
    }
    return () => {
      window.varLiveReport = null
    }
  }, [router.asPath])

  // 收藏与取消收藏直播
  const collected = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      setShowLogin(true)
      return
    }
    channelClickReport({
      channel_name: name
    })
    let res = null
    if (isCollected) {
      res = await liveCancelCollected(liveId, token)
    } else {
      res = await liveCollected(liveId, token)
    }
    if (!res.code) {
      message({ content: isCollected ? '取消收藏成功' : '收藏成功！' })
      setCollected(!isCollected)
    } else {
      message({ content: res.msg })
    }
  }

  // 分享直播
  const urlMemo = useMemo(() => {
    const str = `《${name}》的节目太精彩了，快来星视界一起看！免费高清观看地址：：https://www.histar.tv/live/${currChannelUrl}`
    return str
  }, [liveId])
  useEffect(() => {
    const copyUrl = new Copy('.share-live-btn')
    copyUrl.on('success', () => {
      message({ content: '链接复制成功，分享给好友可领积分兑免费会员~' })
      const token = localStorage.getItem('token')
      if (token) {
        taskFinished({
          completionStatus: 3,
          ydtoken: ''
        })
      }
      scoreTaskFinishedReport({
        points_name: '直播分享'
      })
      liveReport({
        share_status: '链接'
      })
    })
  }, [])

  return (
    <>
      <Responsive className={styles.playContainer}>
        <div className={cm(styles.playBox, styles.playBoxPhone)}>
          <div className={styles.playArea}>
            <div className={styles.play}>
              <VideoPlayer
                type="LIVE"
                playType="HLS"
                from="LIVE"
                isLive={true}
                description={desc}
                keywords={name}
                isCollected={isCollected}
                hideProgress
                hideSpeed
                hideNext
                name={name + '直播'}
                channels={list}
                onError={() => setErrorCode('6')}
                lineArr={lineArr}
                needP2P={true}
              />
            </div>
            <div className={cm(styles.playMenu, 'hideWhenPhone')}>
              <div className={styles.menuLeft}>
                <div className={cm(styles.btn, isCollected ? styles.btnCollected : '')} onClick={collected}>
                  <img src={'/images/' + (isCollected ? 'collect_active.png' : 'collect_page.png')} alt="收藏" />
                  {isCollected ? '已' : ''}收藏
                </div>
                <div className={cm(styles.btn, styles.btnShare, 'share-live-btn')} data-clipboard-text={urlMemo}>
                  <img src="/images/share.png" alt="分享" />
                  分享
                  <img src="/images/corn.webp" alt="corn" className={styles.corn} />
                </div>
              </div>
              <div className={styles.menuRight}>
                <div className={cm(styles.btn, styles.btnMore)} onClick={() => router.push('/download?to=phone')}>
                  <img src="/images/collect_page.png" alt="收藏" />
                  手机随时看
                  <DownloadPhone className={styles.btnHover} />
                </div>
                <div className={cm(styles.btn, styles.btnMore)} onClick={() => router.push('/download?to=tv')}>
                  <img src="/images/tv-download.png" alt="收藏" />
                  TV大屏观看
                  <DownloadTv className={styles.btnHover} />
                </div>
              </div>
            </div>
          </div>
          <div className={cm(styles.sectionBox, 'hideWhenPhone')}>
            <h1 className={cm(styles.titleName, 'textEllipsis')}>{name}</h1>
            <div className={styles.liveTip}>直播频道</div>
            <div className={styles.jujiBox}>
              {list?.map((item, index) => {
                return (
                  <Link
                    href={`/live/${item.url}`}
                    replace
                    key={index}
                    className={cm(styles.jujiItem, item.url == currChannelUrl ? styles.jujiActive : '')}
                  >
                    <img src={item.img} alt={item.name} className={styles.img} />
                    <div className={styles.liveRight}>
                      <div className={cm(styles.liveName, 'textEllipsis')}>{item.name}</div>
                      {item.url === currChannelUrl ? (
                        <Living className={styles.living} />
                      ) : (
                        <img src="/images/live-vip.webp" alt="vip" className={styles.liveIcon} />
                      )}
                    </div>
                  </Link>
                )
              })}
            </div>
          </div>
        </div>
      </Responsive>
      <Layout>
        <section>
          <h1 className={cm(styles.name, 'textEllipsis', styles.titlePhone)}>{name}直播</h1>
          <div className={cm(styles.playMenuPhone, 'hideWhenPc')}>
            <div className={cm(styles.btn, isCollected ? styles.btnCollected : '')} onClick={collected}>
              <img src={'/images/' + (isCollected ? 'collect_active.png' : 'collect_page.png')} alt="收藏" />
            </div>
            <div className={cm(styles.btn, styles.btnShare, 'share-live-btn')} data-clipboard-text={urlMemo}>
              <img src="/images/share.png" alt="分享" />
              <img src="/images/corn.webp" alt="corn" className={styles.corn} />
            </div>
          </div>
          <div className={cm(styles.channelPhone, 'scrollBeautify', 'hideWhenPc')}>
            {list.map((item, index) => {
              return (
                <Link
                  href={`/live/${item.url}`}
                  replace
                  className={cm(styles.channel, item.url === currChannelUrl ? styles.active : '')}
                  key={index}
                >
                  <div className={styles.img}>
                    <Image src={item.img || '/images/horizon.png'} initSrc="/images/horizon.png" alt={item.name} />
                  </div>
                  <span className="textEllipsis">{item.name}</span>
                </Link>
              )
            })}
          </div>
          <p className={cm(styles.introduce, 'hideWhenPc')}>频道介绍</p>
          <article className={styles.desc}>{desc}</article>
        </section>
      </Layout>
    </>
  )
}

export default Index

const formatDesc = (initDesc,name) => {
  let desc = initDesc 
  if(!desc){
    desc = `${name}直播，提供${name}频道24小时高清信号直播，是全天收看${name}精彩节目的不二选择。打开星视界，观看更多精彩直播！`
  }
  if(desc.length > 120){
    desc = desc.slice(0,120) + '...'
  }
  return desc
}
export async function getServerSideProps({ params }) {
  const { id } = params
  const resArr = (await Promise.allSettled([getLiveDesc(id, {}), getGroupChannel(id, {}), getSourceList(id, {})])).map(
    item => {
      if (item.value.code === 0) {
        return item.value?.data || {}
      }
      return {}
    }
  )
  // 去到404页面
  if (isPureNumber(id) || !resArr[0]?.id) return { notFound: true }
  const { name = '', desc = '', liveImg = '' } = resArr[0]
  const layoutProps = {
    noSomeMetaInfo: false,
    url: '/live',
    title: name + '直播 - 高清电视直播在线观看 - 星视界',
    desc: formatDesc(desc,name)
  }
  const haveDrama = name.includes('CCTV') || name.includes('卫视')
  const purl = resArr[2]?.list?.length ? resArr[2].list[0]?.url : ''
  let lineArr = []
  try {
    lineArr = resArr[2].list || []
  } catch (error) {}
  const list = resArr[1]?.channels || []
  const idObj = list?.filter(item => item.url == id)?.pop() || {}
  return {
    props: {
      currChannelUrl: id,
      name,
      haveDrama,
      liveImg,
      desc,
      list,
      purl,
      lineArr,
      layoutProps,
      liveId: idObj?.id || ''
    }
  }
}
